package com.apobates.jforum2.troll.notices.mapper;

import com.apobates.jforum2.troll.notices.ForumLetterReplica;
import com.apobates.jforum2.troll.notices.entity.ForumLetterReceiver;
import com.apobates.jforum2.troll.notices.stub.vo.LetterOutboxVo;
import com.apobates.jforum2.troll.utils.core.DateTimeUtils;
import com.apobates.jforum2.troll.utils.core.api.OptionalEntityTransformMapper;
import java.util.*;
import java.util.function.Function;

public class LetterOutboxVoMapperEntity implements OptionalEntityTransformMapper<ForumLetterReplica, LetterOutboxVo> {

    public static Function<ForumLetterReplica, LetterOutboxVo> mapper(){
        return forumLetterReplica->{
            LetterOutboxVo ov = new LetterOutboxVo();
            ov.setSubject(forumLetterReplica.getTitle());
            ov.setContent(forumLetterReplica.getContent());
            ov.setDatetime(DateTimeUtils.formatClock(forumLetterReplica.getEntryDateTime()));
            ov.setCategory(forumLetterReplica.getTyped().getTitle());
            //
            List<Map<String, String>> reces = new ArrayList<>();
            boolean isEveryOne = false;
            for (ForumLetterReceiver flr : forumLetterReplica.getReceivers()) {
                Map<String, String> tmp = new HashMap<>();
                tmp.put("nickname", flr.getMemberNickname());
                tmp.put("id", flr.getMember() + "");
                reces.add(tmp);
                if (!isEveryOne && 0L == flr.getMember()) {
                    isEveryOne = true;
                }
            }
            ov.setReceives(reces);
            ov.setEveryone(isEveryOne);
            //
            if(!reces.isEmpty()){
                ov.setReceiver(Long.valueOf(reces.get(0).get("id")));
                ov.setReceiverNickname(reces.get(0).get("nickname"));
            }else{
                ov.setReceiver(0L);
                ov.setReceiverNickname("-");
            }
            ov.setReceiverURI(String.format("/member/%d.xhtml", ov.getReceiver()));
            return ov;
        };
    }
    @Override
    public Optional<LetterOutboxVo> transform(Optional<ForumLetterReplica> entity) {
        return entity.map(ins->{
            return mapper().apply(ins);
        });
    }
}
